# from aip import AipOcr
from django.conf import settings


class BaiduOcrClient:
    def __init__(self):
        try:
            # 动态读取配置，避免缓存旧值
            baidu_ocr = settings.BAIDU_OCR
            app_id = baidu_ocr['APP_ID']
            api_key = baidu_ocr['API_KEY']
            secret_key = baidu_ocr['SECRET_KEY']
            
            print(f"初始化百度OCR客户端...")
            print(f"  APP_ID: {app_id} (类型: {type(app_id)})")
            print(f"  API_KEY: {api_key[:10]}...")
            print(f"  SECRET_KEY: {secret_key[:10]}...")
            
            # self.client = AipOcr(app_id, api_key, secret_key)
            print("✅ 百度OCR客户端初始化成功")
        except Exception as e:
            print(f"❌ 百度OCR客户端初始化失败: {e}")
            raise

    def recognize_id_card(self, image_path, side="front"):
        """
        识别身份证正反面
        :param image_path: 图片本地路径或二进制数据
        :param side: "front"（正面）/ "back"（背面）
        :return: 识别结果字典
        """
        try:
            # 读取图片二进制数据
            if isinstance(image_path, str):
                with open(image_path, 'rb') as f:
                    image = f.read()
            else:
                image = image_path  # 若传入的是二进制数据（如前端上传的文件）

            print(f"  图片大小: {len(image)} bytes, 识别面: {side}")

            # 调用百度OCR身份证识别接口
            result = self.client.idcard(image, side)
            
            print(f"  百度OCR返回结果: {result}")

            # 处理返回结果（错误码参考百度文档：https://ai.baidu.com/ai-doc/OCR/dk3h7y5vr）
            if "error_code" in result:
                error_msg = f"识别失败：{result.get('error_msg', '未知错误')} (错误码: {result.get('error_code')})"
                print(f"❌ {error_msg}")
                return {"success": False, "error": error_msg}

            return {
                "success": True,
                "data": result.get("words_result", {})  # 包含姓名、身份证号等字段
            }
        except Exception as e:
            import traceback
            error_detail = traceback.format_exc()
            print(f"❌ OCR识别异常: {e}")
            print(error_detail)
            return {"success": False, "error": f"OCR识别异常：{str(e)}"}